package zz.note.rabbitmq.ttl;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @Author: ZZ
 * @date 2022/2/11
 */
@Component
public class TTLOrderService {
	@Autowired
	private RabbitTemplate rabbitTemplate;
	// 定义交换机
	private String exchangeName = "ttl_direct_exchange";
	// 路由key
	private String routeKey = "ttl";
	// 方式1、通过配置交换机过期时间
	public void makeOrderTtl(String userId) {
		String orderNumer = UUID.randomUUID().toString();
		rabbitTemplate.convertAndSend(exchangeName, routeKey, orderNumer);
	}

	// 方式2、通过配置消息过期时间
	public void makeOrderTtlMessage(String userId) {
		MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
			@Override
			public Message postProcessMessage(Message message) throws AmqpException {
				message.getMessageProperties().setExpiration("5000");
				message.getMessageProperties().setContentEncoding("UTF-8");
				return message;
			}
		};

		String orderNumer = UUID.randomUUID().toString();
		rabbitTemplate.convertAndSend(exchangeName, "ttlmessage", orderNumer,messagePostProcessor);
	}
}
